﻿<%@ WebHandler Language="C#" Class="UploadHousePic" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Chenxin.Lib.Utility;
using Chenxin.Lib.House;
using System.Data;
using System.IO;

public class UploadHousePic : AjaxHandlerBase
{
    //2010-6-17 wang.wei-add
    public UploadHousePic()
    {
        htTypePermit.Add("add", Constants.Permit_UploadHousePic);
    }

    private string CommunityId = "";
    private string Houseid = "";
    private string Pictype = "";
    private string DbPicType = "";
    private string PicTypeName = "";
    private string virtualPath = Constants.FilePath_HousePics;
    private string rootPicUrl = Constants.DIRECTORY;
    private int uploadPicCount = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["HousePicSetCount"]);
    private string httpPath = System.Configuration.ConfigurationManager.AppSettings["Picture.RootUrl"];
    override public void RequestProcess(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        //if (context.Request["OprPersonId"] != null && context.Request["OprPersonId"] != "undefind")
        //{
        //    if (context.Request["OprPersonId"] != CurrentUserInfo.UserId.ToString())
        //    {
        //        context.Response.Write("{success:0,msg:'请上传自己房源的图片！',data:''}");
        //        return;
        //    }
        //}
        if (context.Request["GetAllPic"] != null && context.Request["GetAllPic"] != "undefind")
        {
            Houseid = context.Request["GetAllPic"];
            this.GetAllPicByHouseId(context, Houseid);
            return;
        }
        if (context.Request["DelPic"] != null && context.Request["DelPic"] != "undefind")
        {
            string PicRecoderIds = context.Request["DelPic"];
            List<Chenxin.Lib.House.Entity.House_PicturesInfo> dbPicPath = Chenxin.Lib.House.DAL.House_PicturesInfo.GetListArray("RecordId in (" + PicRecoderIds + ")");
            int result = Chenxin.Lib.House.DAL.House_PicturesInfo.DeleteMore(PicRecoderIds);

            if (result > 0)
            {
                string currPic = "", thurPic = "", WaterPic = "";
                foreach (Chenxin.Lib.House.Entity.House_PicturesInfo pic in dbPicPath)
                {
                    currPic = context.Server.MapPath(Constants.DIRECTORY + pic.OriginalUrl);
                    thurPic = context.Server.MapPath(Constants.DIRECTORY + pic.ThumbnailUrl);
                    WaterPic = context.Server.MapPath(Constants.DIRECTORY + pic.MarkedUrl);
                    if (File.Exists(currPic))
                    {
                        File.Delete(currPic);
                    }
                    if (File.Exists(thurPic))
                    {
                        File.Delete(thurPic);
                    }
                    if (File.Exists(WaterPic))
                    {
                        File.Delete(WaterPic);
                    }
                }
                context.Response.Write("{success:1,msg:'图片删除成功！',data:''}");
            }
            else
            {
                context.Response.Write("{success:0,msg:'图片删除失败！',data:''}");
            }
            return;
        }
        CommunityId = context.Request["CommunityId"];  //楼盘id
        Houseid = context.Request["HouseId"];
        Pictype = context.Request["pictype"];
        switch (Pictype)
        {
            case "1":
                PicTypeName = "HouseForm";
                DbPicType = "房型图";
                break;
            case "2":
                PicTypeName = "Interior";
                DbPicType = "室内图";
                break;
            case "3":
                PicTypeName = "Outdoor";
                DbPicType = "室外图";
                break;
        }


        //检查上传图片是否已超过上限
        int picCount = Chenxin.Lib.House.DAL.House_PicturesInfo.GetHadSetPicCount("HouseId='" + Houseid + "' and PicType='" + DbPicType + "' ");
        if (picCount == uploadPicCount)
        {
            context.Response.Write("{success:0,msg:'图片上传失败！" + Pictype + " 上传已达上限',data:''}");
            return;
        }

        string cutImg = "", thuImg = "", watImg = "";  //图片路径变量 
        cutImg = SaveCutterImage(context);
        if (cutImg != "")
        {
            thuImg = SaveThumbnialImage(context, cutImg);
        }
        if (thuImg != "")
        {
            watImg = SaveWaterMarkImage(context, cutImg);
        }
        if (watImg != "")
        {
            try
            {
                this.AddPicInfo(cutImg, thuImg, watImg);
            }
            catch
            {
                watImg = "";
            }
        }
        if (watImg != "")
        {
            //string picPath = httpPath + watImg;
            context.Response.Write("{success:1,msg:'图片上传成功！',data:''}");
            //context.Response.Write("{success:1,msg:'',data:{" + picPath + "}}");
        }
        else
        {
            context.Response.Write("{success:0,msg:'图片上传失败！',data:''}");
        }

    }

    private void GetAllPicByHouseId(HttpContext context, string houseid)
    {

        DataSet ds = Chenxin.Lib.House.DAL.House_PicturesInfo.GetList("HouseId='" + houseid + "'");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            dr["ThumbnailUrl"] = httpPath + dr["ThumbnailUrl"].ToString();
        }
        //List<Chenxin.Lib.House.Entity.House_PicturesInfo> pic = Chenxin.Lib.House.DAL.House_PicturesInfo.GetListArray("HouseId='"+houseid+"'");
        string result = JsonHelp.Convert2Json(ds.Tables[0]);
        context.Response.Write("{success:1,msg:'',data:{" + result + "}}");
    }

    //*******************************************
    //功能概要       ：保存裁剪后的图片
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：保存裁剪后的图片
    //作成者         ：姚志强
    //作成日         ：2010-03-25
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string SaveCutterImage(HttpContext context)
    {
        string cutterImageUrl = "";
        HttpPostedFile file = context.Request.Files["FileData"];
        string strSavePath = context.Server.MapPath(rootPicUrl + virtualPath + "CutterImage/" + CommunityId + "/" + PicTypeName + "/");
        string fileName = Guid.NewGuid().ToString("N") + ".jpg";
        if (file != null)
        {
            if (!Directory.Exists(strSavePath))
            {
                Directory.CreateDirectory(strSavePath);
            }
            file.SaveAs(strSavePath + fileName);
            cutterImageUrl = virtualPath + "CutterImage/" + CommunityId + "/" + PicTypeName + "/" + fileName;
        }

        return cutterImageUrl;
    }

    //*******************************************
    //功能概要       ：保存压缩后的图片
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：保存压缩后的图片
    //作成者         ：姚志强
    //作成日         ：2010-03-25
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string SaveThumbnialImage(HttpContext context, string OrgPicUrl)
    {

        string ThumbnialImageUrl = "";
        HttpPostedFile file = context.Request.Files["FileData"];
        string strSavePath = context.Server.MapPath(rootPicUrl + virtualPath + "ThumbnialImage/" + CommunityId + "/" + PicTypeName + "/");
        string fileName = Guid.NewGuid().ToString("N") + ".jpg";
        if (file != null)
        {
            if (!Directory.Exists(strSavePath))
            {
                Directory.CreateDirectory(strSavePath);
            }
            Chenxin.Lib.Utility.PictureProcess.MakeThumbnail(context.Server.MapPath(rootPicUrl + OrgPicUrl), strSavePath + fileName, 194, 116, "W");
            ThumbnialImageUrl = virtualPath + "ThumbnialImage/" + CommunityId + "/" + PicTypeName + "/" + fileName;
        }
        return ThumbnialImageUrl;
    }

    //*******************************************
    //功能概要       ：保存水印后的图片
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：保存压缩后的图片
    //作成者         ：姚志强
    //作成日         ：2010-03-25
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string SaveWaterMarkImage(HttpContext context, string OrgPicUrl)
    {
        string WaterMarkImageUrl = "";
        HttpPostedFile file = context.Request.Files["FileData"];
        string strSavePath = context.Server.MapPath(rootPicUrl + virtualPath + "WaterMarkImage/" + CommunityId + "/" + PicTypeName + "/");
        string fileName = Guid.NewGuid().ToString("N") + ".jpg";
        if (file != null)
        {
            if (!Directory.Exists(strSavePath))
            {
                Directory.CreateDirectory(strSavePath);
            }
            string path_sypf = context.Server.MapPath("~/images/Logo/logo.png");
            Chenxin.Lib.Utility.PictureProcess.AddWaterPic(context.Server.MapPath(rootPicUrl + OrgPicUrl), strSavePath + fileName, path_sypf);
            WaterMarkImageUrl = virtualPath + "WaterMarkImage/" + CommunityId + "/" + PicTypeName + "/" + fileName;
        }
        return WaterMarkImageUrl;
    }


    //*******************************************
    //功能概要       ：保存图片地址 
    //参数説明       ：
    //返回值説明     ：
    //功能詳細       ：
    //作成者         ：姚志强
    //作成日         ：2010-03-25
    //修改者         ：
    //修改日         ：
    //*******************************************
    private void AddPicInfo(string cutImg, string thuImg, string watImg)
    {
        Chenxin.Lib.House.Entity.House_PicturesInfo pic_info = new Chenxin.Lib.House.Entity.House_PicturesInfo();
        pic_info.RecordId = Guid.NewGuid();
        pic_info.HouseId = new Guid(Houseid);
        pic_info.PicType = DbPicType;
        pic_info.ThumbnailUrl = thuImg;
        pic_info.OriginalUrl = cutImg;
        pic_info.MarkedUrl = watImg;
        pic_info.Addtime = DateTime.Now;
        pic_info.AddPerson = CurrentUserInfo.UserCode;
        pic_info.AddPersonId = CurrentUserInfo.UserId;
        Chenxin.Lib.House.DAL.House_PicturesInfo.Add(pic_info);
    }


    //*******************************************
    //功能概要       ：各功能单独权限判断
    //参数説明       ：context 请求上下文
    //               ：strMsg 响应消息
    //返回值説明     ：bool
    //功能詳細       ：各功能单独权限判断
    //作成者         ：he.jifeng
    //作成日         ：2010-06-13
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        string op = context.Request.Params["op"];
        bool bRet = false;
        if (op != null)
        {
            op = op.ToLower();
            System.Collections.Hashtable per = new System.Collections.Hashtable();
            System.Collections.Hashtable confine = new System.Collections.Hashtable();

            if (op.Equals("edit") | (op.Equals("checkpermit") && "edit".Equals(context.Request.Params["code"])))
            {
                Chenxin.Lib.House.Entity.House_BaseInfo entUpdHouse = (Chenxin.Lib.House.Entity.House_BaseInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));

                Chenxin.Lib.House.Entity.House_BaseInfo entHouseBase = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(entUpdHouse.HouseId);
                if (entHouseBase == null)
                {
                    strMsg = "{success:0,msg:'数据已变更,请刷新后重新执行操作！',data:''}";
                    return false;
                }

                //权限项
                per.Add("ALL", Constants.Permit_EditHouse_All);
                per.Add("CITY", Constants.Permit_EditHouse_City);
                per.Add("COMPANY", Constants.Permit_EditHouse_Company);
                per.Add("DEPART", Constants.Permit_EditHouse_Department);

                //加入范围
                confine.Add("CityId", entHouseBase.CityId);
                confine.Add("CompanyId", entHouseBase.CompanyId);
                confine.Add("OperatorId", entHouseBase.OprPersonId);

                //检查层级权限
                bRet = CheckPermint(per, confine, chkDepartPermit(entHouseBase, "edit"), out strMsg);
            }
            else
            {
                strMsg = "{success:1,msg:'',data:{permit:true}}";
                bRet = true;
            }
        }
        else
        {
            strMsg = "{success:0,msg:'参数有误！',data:''}";
            bRet = false;
        }
        return bRet;
    }
    //*******************************************
    //功能概要       ：判断编辑部门权限
    //参数説明       ：entBaseInfo 上下文
    //               ：op 操作类型
    //返回值説明     ：bool
    //功能詳細       ：部门内有无编辑房源权限
    //作成者         ：he.jifeng 
    //作成日         ：2010-06-13
    //修改者         ：
    //修改日         ：
    //*******************************************
    public bool chkDepartPermit(Chenxin.Lib.House.Entity.House_BaseInfo entBaseInfo, string op)
    {
        if (entBaseInfo.OprPersonId.Equals(CurrentUserInfo.UserId))
            return true;
        bool bRet = false;
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", entBaseInfo.OprDepartId, CurrentUserInfo.UserId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
        if (list.Count > 0)
        {
            Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation struct_UserDepartRelation = list[0];

            switch (op)
            {
                case "edit":
                    bRet = (struct_UserDepartRelation.CanUploadPicture || struct_UserDepartRelation.CanDeletePicture);
                    break;
                default:
                    bRet = true;
                    break;
            }
        }
        return bRet;
    }
}

